import React, { Component } from 'react';
import {connect} from 'react-redux';
import {Button, Form, Input, Checkbox, Switch, Spin, Radio, Row, Col, Select, Modal, Table} from 'antd'
import { messages } from "share/common";
import Priority from 'components/template/priority';
const FormItem = Form.Item;
const Group = Checkbox.Group;
const RadioGroup = Radio.Group;
const { Option } = Select;
import 'styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss'
import NewConsumerServer from '../new-consumer-server';
import ConsumerUtil from '../consumer-util'
import {message} from "antd/lib/index";

@Form.create()
class CtripEditFrame2 extends Component{

  constructor(props){
    super(props);
    this.state = {
      editData: {}, // 编辑数据
      loading: false,
      mode: 1, // 小客户还是大客户
      priDefalultValue: {}, // 权限数据初始值
      isNew: false, // 是否是新建
      appKeyMap: new Map(),
      recordModalVisible: false,
      recordDataSource: []
    };
    this.columns = [
      {
        title: messages('supplier-1.key730')/*批次号*/,
        dataIndex: 'batchNo',
      },
      {
        title: messages('supplier-1.key731')/*更新日期*/,
        dataIndex: 'updateTime',
      }
    ]
    this.paymentCycles = [
      {
        label: messages('supplier-1.key183')/*自然月*/,
        value: 'M'
      },
      {
        label: messages('supplier-1.key184')/*固定日*/,
        value: 'D'
      },
    ]
    this.accountPeriodDayOptions = new Array(28).fill({}).map((item,i) => {
      item = {
        label: i + 1,
        value: i + 1,
      }
      return item
    })

    this.messageTypes =
      [
        { key: "approvalAuthorize", text: messages('supplier-1.key520')/*审批授权通知*/, content: ["审批人"], value: 1 },
        { key: "approvalResult", text: messages('supplier-1.key521')/*审批结果通知通知人*/, content: ["预定人", "出行人"], value: 1 },
        { key: "itineraryManager", text: messages('supplier-1.key522')/*行程管家通知人*/, content: ["预定人", "出行人"], value: 1 },
        { key: "flightChange", text: messages('supplier-1.key523')/*航变消息通知人*/, content: ["预定人", "出行人"], value: 1 },
        { key: "orderChange", text: messages('supplier-1.key524')/*订单通知*/, content: ["预定人", "出行人"], value: 1 },
        { key: "flightInfo", text: messages('supplier-1.key525')/*航班信息*/, content: ["预定人", "出行人"], value: 1 }
      ]
  }

  componentWillMount() {
    this.getVendorUpdateRecord()
    NewConsumerServer(this).getCtripAPPKeyList().then(res => {
      let appKeyMap = new Map();
      if(res.data && res.data && res.data.length) {
        res.data.map(item => appKeyMap.set(item.appKey, item.appSecurity));
      }
      this.setState({ appKeyMap });
    });
    const {params, tenant} = this.props;
    const initValue = ConsumerUtil.initPriorityData(this.props);
    if(params.companyInfos){
      initValue.distribution = {
        companies: params.companyInfos ? params.companyInfos : []
      }
    }
    this.setState({
      mode: params.levelCode ? (params.isBigCus ? 1 : -1) : 1,
      editData: params,
      isNew: params.levelCode ? false : true,
      priDefalultValue: initValue
    }, this.props.form.resetFields);
  }

  onCancelEdit = () => {
    this.props.close();
  };

  // 大小客户切换回调
  handleModeChange = e => {
    const {editData} = this.state;
    this.setState({
      mode: e.target.value,
    });
    if(e.target.value === 1 && !editData.isBigCus){
      this.props.form.setFieldsValue({'appSecurity': null, 'appKey': null});
    }else{
      this.props.form.resetFields();
    }
  };

  // 保存提交
  onSubmitEdit = () => {
    if(this.isLock){
      return ;
    }
    const { mode } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        const {priDefalultValue, isNew, editData} = this.state;
        const authData = JSON.parse(JSON.stringify(priDefalultValue));
        if (!authData) {
          message.error(messages('supplier-1.key185')/*请填写所属组织*/);
          return;
        }
        if(!authData.distribution && authData.levelCode != 'COMPANY'){
          message.error(messages('supplier-1.key186')/*启用公司不支持通用*/);
          return;
        }
        if(authData.levelCode != 'COMPANY' && authData.distribution.companies.length <= 0){
          message.error(messages('supplier-1.key187')/*请填写公司*/);
          return;
        }
        const pri = {
          ...authData,
          companies: authData.distribution ? authData.distribution.companies.map(item => item.id) : [],
        }
        delete pri.distribution;
        let upParams = Object.assign({},values,pri);
        upParams.isBigCus = mode === 1;
        upParams.tenantId = this.props.tenant.id;
        if (!isNew) {
          upParams = Object.assign({}, editData, upParams);
        }
        upParams.appSecurity = upParams.appSecurity.trim();
        upParams.appKey = upParams.appKey.trim();
        mode != 1 ? upParams.accountID = '' : '';
        if(upParams.accountID!=''){
          if(!(/^[0-9]+$/.test(upParams.accountID)) || upParams.appKey === upParams.accountID){
            message.error(messages('supplier-1.key188')/*accountID输入有误*/);
            return;
          }
        }
        this.isLock = true;

        NewConsumerServer(this).submitCritpData(upParams).then(res => {
          this.isLock = false;
          if (!res.data.passFlag && res.data.message) {
            message.error(res.data.message);
          }else{
            this.props.close(true);
            this.props.form.resetFields();
          }
        });
      }
    })
  };

  getVendorUpdateRecord = () => {
    const {company} = this.props;
    NewConsumerServer(this).getVendorUpdateRecord(company.companyOID, 'ctrip').then(res => {
      let records = res.data.records || []
      records = records.map((record, i) => ({...record, key: i}))
      this.setState({
        recordDataSource: records
      })
    })
  }

  // 新建携程小用户回调
  onCreatAccount = () => {
    if(this.isLock){
      return;
    }
    this.isLock = true;
    NewConsumerServer(this).creatCritpAccount().then(res => {
      this.isLock = false;
      let appKeyMap = new Map();
      if(res.data && res.data.vo) {
        appKeyMap.set(res.data.vo.appKey, res.data.vo.appSecurity);
      }
      this.setState({ appKeyMap });
    });
  };

  onChangeAppKey = value => {
    const { appKeyMap } = this.state;
    this.props.form.setFieldsValue({ 'appSecurity': appKeyMap.get(value) });
  };

  isOpenServer = (value) => {}

  showRecord = (val) => {
    this.setState({
      recordModalVisible: val
    })
  }

  onPriorityChange = (values) => {
    this.setState({
      priDefalultValue: values,
    })
  }

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { code:language } = this.props.language;

    const { editData, loading, mode, appKeyMap, isNew, priDefalultValue, recordModalVisible, recordDataSource } = this.state;
    const { isBigCus, appKey, appSecurity, accountID, openType, isOpenApproval, isOpenPcSso, status } = editData;
    const formLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14}
    }
    const receiptCompanyTypeList = ["月结统一开票"];
    const receiptPersonTypeList = ["预付房型统一开票","预付房型个人开票"];

    return (
      <div className='edit-frame'>
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem label={messages('common.column.status')/*状态*/} {...formLayout}>
              {
                getFieldDecorator('enabled',{
                  initialValue: editData.enabled || false,
                  valuePropName:'checked',
                })(
                  <Switch onChange={this.isOpenServer}/>
                )
              }
            </FormItem>
            <Priority
              top='TENANT'
              formItemLayout={formLayout}
              disabledTop={!isNew}
              companyProps={{disabled: !isNew}}
              defaultValue={priDefalultValue}
              onChange={this.onPriorityChange}
            />
            <h3 style={{borderBottom: 0}}>
              <div className='other-rule-edit-title'>
                {messages('supplier-1.key189')/*服务商参数设置*/}
              </div>
            </h3>
            <div className='new-item-box'>
              <div className='new-item-label-style'>
                <span className='form-label-text-style'>{messages('supplier-1.key190')/*服务类型*/}</span>
              </div>
              <div className='new-item-value-style'>
                <Radio.Group onChange={this.handleModeChange} size={language === 'it_IT' ? 'small' : ''} value={mode === -1 ? -1 : 1} style={{ marginBottom: 16 }}>
                  <Radio.Button value={1}>{messages('supplier-1.key48')/*携程大客户*/}</Radio.Button>
                  <Radio.Button value={-1}>{messages('supplier-1.key49')/*携程小客户*/}</Radio.Button>
                </Radio.Group>
              </div>
            </div>
            {/*需求变更：如果公司已经是小客户则不许新建小客户账号 留了个口子如果是小客户并且还没拿到appKey可以新建，正常应该不会出现*/}
            {mode === -1 && (isBigCus || !appKey) && (
              <Row>
                <Col offset={7} span={16} >
                  <Button type="link" icon="plus" style={{ marginLeft: -15 }} onClick={this.onCreatAccount}>
                    {messages('supplier-1.key191')/*新建携程账户*/}
                  </Button>
                  <p style={{ marginBottom: 32, fontSize: 12 }} className='font-subtitle'>{messages('supplier-1.key192')/*首个携程小客户权限需要在线新建，成功后会回写App Key, App Secret*/}</p>
                </Col>
              </Row>
            )}
            <FormItem label={'App Key'} {...formLayout}>
              {
                getFieldDecorator('appKey',{
                  initialValue: mode === -1 ? [...appKeyMap.keys()][0] : (appKey || ''),
                  rules:[
                    { required:true, message:messages('supplier-1.key193')/*必填*/ }
                  ]
                })(
                  mode === -1 ? (
                    <Select onChange={this.onChangeAppKey}>
                      {[...appKeyMap.keys()].map(option => <Option value={option}>{option}</Option>)}
                    </Select>
                  ) :
                    <Input />
                )
              }
            </FormItem>
            <FormItem label={'App Secret'} {...formLayout}>
              {
                getFieldDecorator('appSecurity',{
                  initialValue: mode === -1 ? [...appKeyMap.values()][0] : (appSecurity || ''),
                  rules:[
                    { required:true, message:messages('supplier-1.key193')/*必填*/ }
                  ]
                })(
                  mode === -1 ? <Select disabled/> : <Input />
                )
              }
            </FormItem>
            <FormItem label={'Account ID'} {...formLayout} style={mode === -1 ? {display: 'none'}: {}}>
              {
                getFieldDecorator('accountID',{
                  initialValue: accountID || '',
                })(
                   <Input />
                )
              }
            </FormItem>
            {ConsumerUtil.getTitleComponent(messages('supplier-1.key194')/*服务商应用类型设置*/)}
            {ConsumerUtil.getCtripForm(getFieldDecorator,messages('supplier-1.key195')/*应用类型*/,'Supplier', editData)}

            {ConsumerUtil.getTitleComponent(messages('supplier-1.key196')/*申请单相关设置*/, 16)}
            {ConsumerUtil.getCtripForm(getFieldDecorator,messages('supplier-1.key197')/*行程上可选该服务商*/,'Approval', editData)}

            {ConsumerUtil.getTitleComponent(messages('supplier-1.key198')/*PC端入口*/, 16)}
            {ConsumerUtil.getCtripForm(getFieldDecorator,messages('supplier-1.key199')/*服务商预订首页*/,'PCSso', editData)}
            {ConsumerUtil.getCtripForm(getFieldDecorator,messages('supplier-1.key200')/*服务商订单列表*/,'PCOrder', editData)}

            {ConsumerUtil.getTitleComponent(messages('supplier-1.key201')/*人员信息同步设置*/, 16)}
            <FormItem className='form-label-style' label={messages('supplier-1.key202')/*人员职级*/} {...formLayout}>
              {
                getFieldDecorator('isSyncRankName',{
                  initialValue: editData.isSyncRankName || false,
                  valuePropName: 'checked'
                })(
                  <Checkbox>{messages('supplier-1.key203')/*人员信息同步时同步人员职级*/}</Checkbox>
                )
              }
              <a className='form-item-tip'>{messages('supplier-1.key204')/*职级同步仅支持携程大客户，同步前请确保已在携程维护职级列表*/}</a>
            </FormItem>
            <FormItem className='form-label-style' label={messages('supplier-1.key205')/*邮件通知*/} {...formLayout}>
              {
                getFieldDecorator('isSendEmail',{
                  initialValue: editData.isSendEmail || false,
                  valuePropName: 'checked'
                })(
                  <Checkbox>{messages('supplier-1.key206')/*开通成功后邮件通知员工*/}</Checkbox>
                )
              }
            </FormItem>
            {ConsumerUtil.getTitleComponent(messages('supplier-1.key207')/*预订设置*/)}
            <FormItem label={messages('supplier-1.key97')/*国际机票舱位屏蔽*/} {...formLayout}>
              {
                getFieldDecorator('intlCClassFlag',{
                  initialValue: editData.intlCClassFlag || false,
                  valuePropName:'checked',
                })(
                  <Switch/>
                )
              }
            </FormItem>
            { getFieldValue('intlCClassFlag') && ConsumerUtil.getCtripForm(getFieldDecorator," ",'Class', editData)}
            <FormItem label={messages('supplier-1.key208')/*国内机票两舱控制*/} {...formLayout}>
              {
                getFieldDecorator('bookClassFlag',{
                  initialValue: editData.bookClassFlag || false,
                  valuePropName:'checked',
                })(
                  <Switch/>
                )
              }
            </FormItem>
            <FormItem className='form-label-style' label=" " {...formLayout}>
              {
                getFieldValue('bookClassFlag') && getFieldDecorator('isBookClass',{
                  initialValue: editData.isBookClass || false,
                  valuePropName: 'checked'
                })(
                  <Checkbox>{messages('supplier-1.key209')/*可预订头等舱/商务舱*/}</Checkbox>
                )
              }
            </FormItem>
            {ConsumerUtil.getCtripForm(getFieldDecorator,messages('supplier-1.key210')/*不可帮非员工预订*/,'TRFlag', editData)}
            <FormItem className='form-label-style' label={messages('supplier-1.key211')/*酒店总夜间数控制*/} {...formLayout}>
              {
                getFieldDecorator('isOpenTravelerCount',{
                  initialValue: editData.isOpenTravelerCount || false,
                  valuePropName: 'checked'
                })(
                  <Checkbox>{messages('supplier-1.key35')/*启用temp*/}</Checkbox>
                )
              }
            </FormItem>
            <FormItem className='form-label-style' label={messages('supplier-1.key212')/*预定需提前申请*/} {...formLayout}>
              {
                getFieldDecorator('isOpenApproval',{
                  initialValue: editData.isOpenApproval || false,
                  valuePropName: 'checked'
                })(
                  <Checkbox>{messages('supplier-1.key35')/*启用temp*/}</Checkbox>
                )
              }
            </FormItem>
            <h3 style={{borderBottom: 0, marginBottom: 14}}>
              <div className='other-rule-edit-title' style={{marginTop: 32}}>
                {messages('supplier-1.key213')/*审批单前置管控*/}
                <a className='form-ctrip-title-tip'>{messages('supplier-1.key214')/*员工进入携程查询页时，系统自动带入已选审批单上的信息并进行管控；请选择需要前置管控的字段。*/}</a>
              </div>
            </h3>
            {ConsumerUtil.getCtripForm(getFieldDecorator,messages('supplier-1.key215')/*机票前置管控*/,'airFields', editData)}
            {ConsumerUtil.getCtripForm(getFieldDecorator,messages('supplier-1.key216')/*酒店前置管控*/,'hotelFields', editData)}
            {ConsumerUtil.getTitleComponent(messages('supplier-1.key526')/*审批单时间落地规则*/, 16)}
            <FormItem className='form-label-style' label={messages('supplier-1.key526')/*审批单时间落地规则*/} {...formLayout}>
              {
                getFieldDecorator('applicationSyncDateRule',{
                  initialValue: editData.applicationSyncDateRule  || 2,
                })(
                  <RadioGroup>
                    <Radio value={1}>{messages('supplier-1.key527')/*出发到达对应映射*/}</Radio>
                    <Radio value={2}>{messages('supplier-1.key528')/*出发到达映射开始结束*/}</Radio>
                  </RadioGroup>
                )
              }
            </FormItem>
            {ConsumerUtil.getTitleComponent(messages('supplier-1.key217')/*审批单管控*/, 16)}
            <FormItem className='form-label-style' label={messages('supplier-1.key218')/*乘客管控*/} {...formLayout}>
              {
                getFieldDecorator('passengerControl',{
                  initialValue: editData.passengerControl || 'E',
                })(
                  <RadioGroup>
                    <Radio value='E'>{messages('supplier-1.key219')/*按工号*/}</Radio>
                    <Radio value='N'>{messages('supplier-1.key220')/*按姓名*/}</Radio>
                  </RadioGroup>
                )
              }
            </FormItem>
            {ConsumerUtil.getTitleComponent(messages('supplier-1.key221')/*APP首页/PC端入口单点登录设置*/)}
            <FormItem className='form-label-style' label={messages('supplier-1.key222')/*跳转至携程商旅首页*/} {...formLayout}>
              {
                getFieldDecorator('returnHome',{
                  initialValue: editData.returnHome || false,
                  valuePropName: 'checked'
                })(
                  <Checkbox>{messages('supplier-1.key35')/*启用temp*/}</Checkbox>
                )
              }
            </FormItem>
            {ConsumerUtil.getTitleComponent(messages('supplier-1.key529')/*开票方案（酒店）*/)}
            <FormItem className='form-label-style' label={messages('supplier-1.key265')/*公司支付*/} {...formLayout}>
              {
                getFieldDecorator('receiptCompanyType',{
                  initialValue: editData.receiptCompanyType || receiptCompanyTypeList[0],
                })(
                  <RadioGroup>
                    <Radio value={receiptCompanyTypeList[0]}>{messages('supplier-1.key530')/*月结统一开票*/}</Radio>
                  </RadioGroup>
                )
              }
            </FormItem>
            <FormItem className='form-label-style' label={messages('supplier-1.key264')/*个人支付*/} {...formLayout}>
              {
                getFieldDecorator('receiptPersonType',{
                  initialValue: editData.receiptPersonType  || receiptPersonTypeList[1],
                })(
                  <RadioGroup>
                    <Radio value={receiptPersonTypeList[0]}>{messages('supplier-1.key531')/*预付房型统一开票*/}</Radio>
                    <Radio value={receiptPersonTypeList[1]}>{messages('supplier-1.key532')/*预付房型个人开票*/}</Radio>
                  </RadioGroup>
                )
              }
            </FormItem>



            {ConsumerUtil.getTitleComponent(messages('supplier-1.key223')/*消费商账期*/)}
            <div className='new-item-box'>
              <div className='new-item-label-style'>
                <span className='form-label-text-style'>{messages('supplier-1.key224')/*账期*/}</span>
              </div>
              <div className='new-item-value-style' style={{display: 'flex'}}>
                <FormItem>
                  {
                    getFieldDecorator('accountPeriodType',{
                      initialValue: editData.accountPeriodType || 'M',
                    })(
                      <Select className="select-size--m">
                        {this.paymentCycles.map(item => <Option value={item.value}>{item.label}</Option>)}
                      </Select>
                    )
                  }
                </FormItem>
                {
                  getFieldValue('accountPeriodType') === 'D' ? (
                    <div className='payment-wrapper'>
                      <span className='label--sub'>{messages('supplier-1.key225')/*每月*/}</span>
                      <FormItem>
                        {
                          getFieldDecorator('accountPeriodDay',{
                            initialValue: editData.accountPeriodDay || 1,
                          })(
                            <Select className="select-size--s">
                              {this.accountPeriodDayOptions.map(item => <Option value={item.value}>{item.label}</Option>)}
                            </Select>
                          )
                        }
                      </FormItem>
                      <span className='label--sub'>{messages('supplier-1.key226')/*日*/}</span>
                    </div>
                  ): ''
                }
              </div>
            </div>
            <div className="record">
              {messages('supplier-1.key760')/*查询AccountID对应的最近三个批次的*/}
              <a onClick={() => this.showRecord(true)}>{messages('supplier-1.key761')/*更新日志*/}</a>
            </div>
            <h3 style={{borderBottom: 0, marginBottom: 14}}>
              <div className='other-rule-edit-title' style={{marginTop: 32}}>
                {messages('supplier-1.key533')/*消息推送设置*/}
                <a className='form-ctrip-title-tip'>{messages('supplier-1.key534')/*需要携程开通事件推送接口，并开通对应的消息类型，需要携程开通“事件推送”接口*/}</a>
              </div>
            </h3>
            <div style={{display:"flex"}}>
            <div style={{flex:1}}>
                <span className="message-push-label">{messages('supplier-1.key535')/*消息推送*/}</span>
            </div>
            <FormItem style={{flex:4,paddingLeft:"20px"}} {...formLayout}>
              {
                this.messageTypes.map(({key,value,text,content}) => {
                  return <div>
                    {
                      getFieldDecorator(`${key}MsgFlag`, {
                        initialValue: editData[`${key}MsgFlag`] || false,
                        valuePropName: 'checked'
                      })(
                        <Checkbox>{text}</Checkbox>
                      )
                    }
                    {
                      getFieldValue(`${key}MsgFlag`) && getFieldDecorator(`${key}Value`, {
                        initialValue: editData[`${key}Value`] || value,
                      })(
                        <RadioGroup>
                          {
                            content.map((item,idx)=> (<Radio value={idx+1}>{item}</Radio>))
                          }
                        </RadioGroup>
                      )
                    }
                  </div>
                })
              }

            </FormItem>
            </div>
          </Form>
        </Spin>
        <br/><br/><br/><br/>
        <div className='affix-bottom'>
          <Button type="primary"  onClick={this.onSubmitEdit} loading={loading}>
            {messages('common.ok')/*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>
            {messages('common.cancel')/*取消*/}
          </Button>
        </div>
        <Modal
          visible={recordModalVisible}
          closable
          title={messages('supplier-1.key733')/*批次日志*/}
          onCancel={() => this.showRecord(false)}
          footer={[
            <Button
              key="submit"
              type="primary"
              onClick={() => this.showRecord(false)}>
              {messages('common.ok')/*确定*/}
            </Button>
          ]}
        >
          <div className="record-modal-content" style={{maxHeight: '300px', overflow: 'scroll'}}>
            <Table columns={this.columns} dataSource={recordDataSource} pagination={false} size="small" />
          </div>
        </Modal>
      </div>
    )
  }
}


CtripEditFrame2.getEditData = (record, data, index) => {
  return record;
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    company: state.login.company,
    language: state.main.language,
  }
}

export default connect(mapStateToProps)(CtripEditFrame2);


